import { Button, Modal,message,Row,Col, Spin} from 'antd';
import isEmpty from 'lodash/isEmpty'
import debounce from 'lodash/debounce'
import cloneDeep from 'lodash/cloneDeep'
import toString from 'lodash/toString'
import forEach from 'lodash/forEach'
import { WeaAlertPage, WeaTools,WeaTableEdit,WeaSearchGroup,WeaRightMenu, WeaFormItem, WeaTab} from 'ecCom'
import {WeaSwitch} from 'comsMobx';
import { inject, observer} from 'mobx-react';
import * as mobx from 'mobx';
import {i18n} from '../../public/i18n';
import {
	WeaLocaleProvider
} from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

const toJS = mobx.toJS;

@inject('hrmPersonal')
@inject('hrmCard')
@observer
class Personal extends React.Component {
  componentDidMount(){
    const {hrmCard} = this.props;
    hrmCard.setTopButtons(this.getTopButtons.bind(this));
    hrmCard.setTopRightMenus(this.getRightMenu.bind(this));
    hrmCard.setTopShowDropIcon(true);
    this.init();
  }
  init = () => {
    const {hrmPersonal, hrmCard, setParentRightMenu} = this.props;
    const hrmId = this.props.params.hrmId || '';
    hrmPersonal.init();
    hrmPersonal.hrmId=hrmId;
    hrmPersonal.getData();
  }
  getTabChildren = () => {
    const {hrmPersonal} = this.props;
    let {tableInfo, isEditor, tabkey,onRowSelect,selectedRowKeys} = hrmPersonal;
    let tabChildren = [];
    tableInfo = toJS(tableInfo);
    tableInfo && tableInfo.map((t,i)=>{
        if(tabkey==i){
          if(t.hide){

          }else{
            tabChildren.push(
              <WeaTableEdit ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEdit@b813my@${i}`}
                  ref={(ref)=>hrmPersonal.setPersonalEditTables(ref)}
                  showTitle={isEditor}
                  // title={'列表信息'}
                  addFirstRow={isEditor}
                  columns={t.tabinfo.columns}
                  datas={t.tabinfo.datas}
                  onChange={this.tableEditChange}
                  selectedRowKeys={toJS(selectedRowKeys)}
                  onRowSelect={keys => onRowSelect(keys)}
                  onBtnsSelect={key=>this.onBtnsSelect(key,i)}
                  viewAttr={isEditor?2: 1}
                  getRowSelection={isEditor? (rowSelection)=>{
                    Object.assign(rowSelection,{
                      getCheckboxProps: record => ({
                        disabled: record.viewAttr === 1,    // 配置无法勾选的列
                      })
                    })
                    return rowSelection;
                  }: ()=>null}
              />
            );
          }
        }
    })
    return tabChildren;
  }
  onBtnsSelect = (key, index) => {
    const {
      hrmPersonal
    } = this.props, {
      tableInfo,
      selectedRows,
      setSelectedRowKeys,
      selectedRowKeys
    } = hrmPersonal;

    const datas = tableInfo[index].tabinfo.datas;
    if (key === 'copy') {
       tableInfo[index].tabinfo.datas = datas.map( (data,i) => {
        if (!selectedRows[index].includes(i)) {
          data.viewAttr = 2;
        }
        return data
       })
    }
    if (key === 'delete') {
     tableInfo[index].tabinfo.datas =  datas.map( (data,i) => {
      if (selectedRows[index].includes(i)) {
        data.viewAttr = 1;
      }
      return data
     });
     setSelectedRowKeys(selectedRowKeys.filter(row => !selectedRows[index].includes(row)))
    }
  }

  getSearchs = () => {
    const {hrmPersonal} = this.props;
    let {form, conditions, isEditor} = hrmPersonal;
    const {isFormInit} = form;
    let group = [];
    let tipPosition = 'bottom';
    window.e9HideFormFieldKeys = [];
    isFormInit && conditions.forEach((c, i) =>{
        let items = [];
        c.items.forEach( (field, j) => {
          if(c.hide || (!isEmpty(field.otherParams) && field.otherParams.hide)){
            window.e9HideFormFieldKeys.push(field.domkey[0]);
          }else{
            items.push({
                com:(<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@vh6j67@${j}`}
                    underline={!isEditor}
                    label={`${field.label}`}
                    error={form.getError(field)}
                    tipPosition={tipPosition}
                    labelCol={{span: `${window.HrmLabelCol}`}}
                    wrapperCol={{span: `${window.HrmWrapperCol}`}}>
                      <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@d4vaqk@${j}`} fieldConfig={field} form={form}/>
                    </WeaFormItem>),
                colSpan: 1
              });
          }
        });
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@x9hby9@${i}`} className={`${isEditor?'hrm-center':''}`}
          needTigger={true} hide={c.hide} title={c.title} showGroup={c.defaultshow} items={items} col={window.HrmGroupCol}/>)
    });
    return group;
  }
  tableEditChange = (data) => {
    const {hrmPersonal} = this.props;
    let {tabkey = '0', tableInfo} = hrmPersonal;
    tableInfo = toJS(tableInfo);
    let d = cloneDeep(tableInfo);
    d[Number(tabkey)].tabinfo.datas = data;
    hrmPersonal.updateTableInfo(d);
  }
  onTabChange = (key) => {
    const {hrmPersonal} = this.props;
    hrmPersonal.changeTab(key);
  }

  getRightMenu = () => {
    const {hrmPersonal, hrmCard} = this.props;
    const {isEditor, buttons,hrmId} = hrmPersonal;
    let arr = [];
    try{
      if(buttons.hasEdit){
          if (isEditor){
              arr = [{
                  icon: <i className='icon-coms-common'/>,
                  content: i18n.button.save(),
                  key: 'save',
                  onClick: key =>{
                    this.saveEditCard();
                  }
                }, {
                  icon: <i className='icon-coms-go-back'/>,
                  content: i18n.button.back(),
                  key: 'back',
                  onClick: key =>{
                    this.backCard();
                  }
                }]
          } else {
              arr = [{
                      icon: <i className='icon-coms-edit'/>,
                      content:i18n.button.modify(),
                      key: 'editCard',
                      onClick: key =>{
                          this.editCard();
                      }
                  }
              ]

              arr.push(
                {
                  icon: <i className='icon-coms-Print-log'/>,
                  content:i18n.button.log(),
                  key: 'showLog',
                  onClick: key =>{
                    window.setLogViewProps({logSmallType:i18n.smallType.HRM_RSOURCE_CARD_PERSONAL,targetId:hrmId});
                  }
                }
              )
          }
      }
    }catch(e){}
    return arr;
  }
  
  getTopButtons = () => {
    const {hrmPersonal} = this.props;
    const {isEditor, buttons} = hrmPersonal;
    const save = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@pkes6y`} type="primary" onClick={this.saveEditCard} >{i18n.button.save()}</Button>;
    const back = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@pl1fw8`} type="primary" onClick={this.backCard} >{i18n.button.back()}</Button>;
    const edit = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vkeda5`} type="primary" onClick={this.editCard} >{i18n.button.modify()}</Button>;
    const btns = [];
    try{
      if (isEditor) {
        if (buttons.hasSave) {
          btns.push(save);
          btns.push(back);
        }
      } else {
        if (buttons.hasEdit) {
          btns.push(edit);
        }
      }
    }catch(e){}
    return btns;
  }
  editCard = () => {
    const {hrmPersonal} = this.props;
    hrmPersonal.edit();
  }
  saveEditCard = () => {
    const {hrmPersonal} = this.props;
    hrmPersonal.save();
  }
  backCard = () => {
    this.init();
  }
  render() {
    const {hrmPersonal} = this.props;
    const {loading, tabkey, tabInfo, date, tableInfo, hasRight} = hrmPersonal;

    if(!hasRight){
      return (
        <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@387kx5`}>
          <div style={{ color: '#000' }}>{i18n.message.authFailed()}</div>
        </WeaAlertPage>
      )
    }
    //let showDetialTable = !isEmpty(tableInfo.filter(t => !t.hide));
    try{
      return  (
          <div className='hrm-my-cardInfo' style={{height:'100%', position: 'relative'}}>
              <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@4fj4z2`} spinning={loading}>
                      {this.getSearchs()}
                      {
                        !isEmpty(tabInfo) && <div className='hrm-my-cardInfo_detial_tabs'>
                        <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@vjrq63`}
                            type='card'
                            keyParam='key'
                            datas={toJS(tabInfo)}
                            selectedKey={tabkey}
                            onChange={ v => {
                                hrmPersonal.updateTabkey(v);
                            }}
                        />
                        {this.getTabChildren()}
                      </div>
                      }
              </Spin>
          </div>
      )
    }catch(e){
      return <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@h1wgnu`}>
          <div style={{ color: '#000' }}>{i18n.message.authFailed()}</div>
      </WeaAlertPage>
    }
  }
}

export default Personal;